const App = {
    mixins: [Save], // 配置文件，路径/utils/mixins.js
    data() {
        return {
            category: [], // 视频分类数据
            study_files_tag: [], // 全部视频标签数据
            themeTags: [], // 题材标签数据（Parent_SerialNumber为VT0000000000017）
            fileList: [],
            childDataForm: [], // 子表表单数据
            childDataForm1: [],
            dataForm: {
                Row_Status: '2',
                Theme_Tag_SerialNumber: [], // 多选题材标签
                Introduction:'',
                Study_Files_Content:'',
            },
            Theme_Tag_SerialNumber: [],
            loading: false // 上传加载状态
        };
    },
    mounted() {

        this.getCategory();
        this.getFileTags();

    },
    watch: {
        'dataForm.Study_Files_SerialNumber'() {
            // this.loadSavedTags();
            if (this.dataForm.Study_Files_Content) {
                this.fileList.push({
                    name: this.dataForm.Study_Files_Content
                })
            }

        },
        childDataForm(val){
            console.log(val);
            this.Theme_Tag_SerialNumber = val.filter(i=>i.Row_Status != '1').map(i=>i.Study_File_Tag_SerialNumber)
        }
    },
    methods: {
        // 加载已保存的标签数据
        loadSavedTags() {
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableName`,
                type: "POST",
                data: {
                    Data: 'study_files_mapping_tag',
                    Condition: `Study_Files_SerialNumber='${this.nodeKey}'`
                },
                success: (data) => {
                    // 直接保存所有标签ID到表单
                    const savedTags = data.map(tag => tag.Study_File_Tag_SerialNumber);
                    this.dataForm.Theme_Tag_SerialNumber = savedTags;
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                }
            });
        },
        async handleChange(file) {
            if (!file.name.includes('（上传中）') && !file.name.includes('（上传成功）')) {
                file.name = file.name + "（上传中）";
            }
        },
        async customUpload(options) {
            const { file } = options;
            this.loading = true;
            this.$emit('progress', this.loading);
            const result = await this.uploadBinaryFile(file);
            if (result.status == 'success') {
                this.fileList.push(file);
                options.onSuccess(result);
                this.dataForm.Study_Files_Content = file.name;
                this.childDataForm1 = [...this.childDataForm1, ...result.FilesPath.map(item => {
                    return {
                        Study_Files_Details_Content: item
                    }
                })]
                // 
                this.$message.success({ message: '上传成功', duration: 1500 })
            } else {
                this.$message.error({ message: '上传失败', duration: 1500 });
            }
            this.loading = false;
        },
        handleSuccess(result, file, fileList) {
            if (result) {
                fileList.filter(i => i.uid == file.uid).forEach(item => {
                    item.name = item.name.replace('（上传中）', '（上传成功）');
                    item.Attachment_URL = result.fileName;
                })
            }
        },
        handleRemove(file, fileList = []) {
            this.fileList = fileList;
            this.dataForm.Study_Files_Content = '';
            if (this.action == 'Add') {
                this.childDataForm1 = [];
            } else if (this.action == 'Modify') {
                if (this.childDataForm1.some(i => i.Row_Status == '0')) {
                    this.childDataForm1.forEach(item => {
                        item.Row_Status = '1'
                    })
                } else {
                    this.childDataForm1 = this.childDataForm1.filter(i => i.Row_Status == '1');
                }
            }
        },
        async uploadBinaryFile(file) {
            try {
                const response = await fetch(
                    mh + "/officeOperation/convertPDFToImage",
                    {
                        method: "POST",
                        headers: {
                            "Content-Type": "application/octet-stream",
                            "X-File-Name": encodeURIComponent(file.name),
                            "X-File-Size": file.size,
                            "X-File-Type": file.type,
                            "AccessToken": getCookie("token"),
                        },
                        body: file,
                    }
                );
                try {
                    const result = await response.json();
                    return result;
                } catch (error) {
                    removeCookie("token");
                    removeCookie("user");
                    sessionStorage.setItem("REDIRECT", "登录已过期，请重新登录！");
                    window.parent.document.location.href = absolutepath() + 'index.html';
                }

            } catch (error) {
                throw error;
            }
        },
        // 获取视频分类数据
        getCategory() {
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableName`,
                type: "POST",
                data: {
                    Data: 'study_files_category',
                    Condition: "Row_Status='0'",
                },
                success: (data) => {
                    this.category = data;
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json",
            });
        },

        // 获取视频标签数据并分类
        getFileTags() {
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableName`,
                type: "POST",
                data: {
                    Data: 'study_files_tag',
                    Condition: "Row_Status='0'",
                },
                success: (data) => {
                    // 直接使用全部标签数据
                    this.study_files_tag = data;
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json",
            });
        },

        // 返回上一页
        goBack() {
            history.back();
        },

        async handleSubmit() {
            const allValid = await this.validateAllForms();
            if (allValid) {
                this.loading = true;
                let ls_URL = window.location.href;
                const action = getQueryObject(ls_URL, "action");   // 获取 action 参数
                let lJSONObject_Data_Options = new Object();
                lJSONObject_Data_Options = JSON.parse(document.getElementById("MainTable").getAttribute("data-options"));

                let ls_MainTableName = lJSONObject_Data_Options.TableName;
                let ls_DataForm = lJSONObject_Data_Options.form;
                let ls_primary_key = lJSONObject_Data_Options.primary_key;

                // this.dataForm.Theme_Tag_SerialNumber.forEach(item=>{
                //     this.childDataForm.push({ 	
                //         Study_Files_SerialNumber:this.dataForm.Study_Files_SerialNumber,
                //         Study_File_Tag_SerialNumber:item
                //     })
                // })
                if (action == "Add") {
                    this.Theme_Tag_SerialNumber.forEach((item) => {
                        this.childDataForm.push({
                            Study_File_Tag_SerialNumber: item
                        });
                    });
                } else if (action == "Modify") {
                    this.Theme_Tag_SerialNumber.forEach((item) => {
                        let obj = this.childDataForm.filter(i => i.Study_File_Tag_SerialNumber == item)[0];
                        if (obj) {
                            obj.Row_Status = "0";
                        } else {
                            this.childDataForm.push({
                                Study_Files_SerialNumber: this.dataForm.Study_Files_SerialNumber,
                                Study_File_Tag_SerialNumber: item,
                            });
                        }
                    });
                    this.childDataForm.forEach((item) => {
                        if (!this.Theme_Tag_SerialNumber.some((i) => i == item.Study_File_Tag_SerialNumber)) {
                            item.Row_Status = "1";
                        }
                    });
                }
                //  = [...this.dataForm.Theme_Tag_SerialNumber,...this.dataForm.Background_Tag_SerialNumber]
                //没有子表下面内容就会报错，try/catch抛出异常
                try {
                    //可能涉及多个子表
                    document.getElementById("ChildTable").querySelectorAll(".el-descriptions").forEach(item => {
                        if (item.hasAttribute('data-options')) {
                            let lJSONObject_ChildData_Options = new Object();
                            lJSONObject_ChildData_Options = JSON.parse(item.getAttribute("data-options"));

                            let ls_ChildTableName = lJSONObject_ChildData_Options.TableName;
                            let ls_ChildDataForm = lJSONObject_ChildData_Options.form;
                            // let ls_ParentTableName = lJSONObject_ChildData_Options.ParentTableName;
                            if (this[ls_DataForm][ls_primary_key]) {
                                this[ls_ChildDataForm].forEach(item => {
                                    item[ls_primary_key] = this[ls_DataForm][ls_primary_key];
                                })
                            }
                            //建立子表结构体
                            let JSONArray_ChildRecord = new Array();
                            JSONArray_ChildRecord = this[ls_ChildDataForm];
                            if (!this[ls_DataForm].Children) {
                                this[ls_DataForm].Children = new Object();
                            }
                            this[ls_DataForm].Children[ls_ChildTableName] = JSONArray_ChildRecord;
                        }
                    })
                } catch (error) {

                }
                //建立新增提交结构
                let lJSONObject_DataSet = new Object();
                if (action == 'Add') {
                    if (this.nodeKey) {
                        this[ls_DataForm].Parent_SerialNumber = this.nodeKey;
                    }
                    this[ls_DataForm].Study_Files_Publish_Datetime = getYMDHMSDate();
                    let lJSONArray_Record = new Array();
                    lJSONArray_Record.push(this[ls_DataForm]);
                    let lJSONObject_Table = new Object();
                    lJSONObject_Table[ls_MainTableName] = lJSONArray_Record;
                    lJSONObject_DataSet[action] = lJSONObject_Table;
                } else if (action == 'Modify') {
                    const { add, modify } = this.deal(this[ls_DataForm]);
                    let lJSONArray_Record = new Array();
                    lJSONArray_Record.push(modify);

                    let lJSONObject_Table = new Object();
                    lJSONObject_Table[ls_MainTableName] = lJSONArray_Record;

                    lJSONObject_DataSet[action] = lJSONObject_Table;
                    lJSONObject_DataSet['Add'] = new Object();
                    if (add != null) {
                        let lJSONArray_Record_Add = new Array();
                        lJSONArray_Record_Add.push(add);

                        let lJSONObject_Table_Add = new Object();
                        lJSONObject_Table_Add[ls_MainTableName] = lJSONArray_Record_Add;

                        lJSONObject_DataSet['Add'] = lJSONObject_Table_Add;
                    }
                }

                console.log(lJSONObject_DataSet);

                let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
                lJSONObject_DataSet['Add']['base_operation_log'] = [{
                    Operation_Type: '0',
                    Operation_Path: this.relativePath,
                    Operation_Main,
                    Operation_Interface: "generalSaveByRequestBody",
                    Operation_IP: getIpAddress()
                }]
                submitSave(lJSONObject_DataSet, (res) => {
                    if (res.Status == 'success') {
                        window.location.href = './index.html'
                    }
                    this.loading = false;
                })
            } else {
                this.$message({
                    message: '存在未填写的必填项！',
                    type: 'warning'
                });
            }
        },

        // 上传成功回调
        success(res) {
            this.dataForm.Study_File_Path = res.Path;
        },

        // 上传进度回调
        progress(loading) {
            this.loading = loading;
        },

        // 新增标签项（如果需要）
        handleAdd(formName) {
            if (this.action === 'Add') {
                this[formName].push({});
            } else if (this.action === 'Modify') {
                let lJSONObject_Data_Options = new Object();
                lJSONObject_Data_Options = JSON.parse(document.getElementById("MainTable").getAttribute("data-options"));
                let ls_primary_key = lJSONObject_Data_Options.primary_key;
                let lJSONObject_Data = new Object();
                lJSONObject_Data[ls_primary_key] = this.nodeKey;
                this[formName].push(lJSONObject_Data);
            }
        },

        // 删除标签项（如果需要）
        handleRemove1(formName) {
            if (this.action === 'Add') {
                if (this[formName].length > 0) {
                    this[formName].pop();
                } else {
                    this.$message({
                        message: '不能再删除了',
                        type: 'warning'
                    });
                }
            } else if (this.action === 'Modify') {
                if (this[formName].filter(item => item.Row_Status != '1').length > 0) {
                    let i = this[formName].filter(item => item.Row_Status != '1').length - 1;
                    let obj = this[formName].filter(item => item.Row_Status != '1')[i];
                    if (!Object.keys(obj).some(item => item.includes('_Original'))) {
                        this[formName].pop();
                    } else {
                        this.$confirm('该操作将删除此条数据,是否继续?', '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning',
                        }).then(() => {
                            this[formName].filter(item => item.Row_Status != '1')[i].Row_Status = '1';
                        }).catch(() => {
                            this.$message({
                                type: 'warning',
                                message: '已取消删除'
                            });
                        });
                    }
                } else {
                    this.$message({
                        message: '不能再删除了',
                        type: 'warning'
                    });
                }
            }
        },

    }
};

const { createApp, ref } = Vue;
const app = createApp(App);
app.use(ElementPlus, { locale: zhCn });

// 引入全部图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component);
}

app.component('yl-upload', ylUpload);
const ElMessage = ElementPlus.ElMessage;
app.mount("#app");